Complete REST API Design
API design is something that as a backend engineer you will spend a lot of time working on and thinking about and it is one of the most important videos in this playlist and in this video we are going to talk a lot about uh designing apis a lot of Concepts surrounding uh apis in general and we'll be mostly focusing on rest API there are different technologies that people use
to build API uh we have RPC calls and we have graphql etc etc so in this one we are going to only focus on rest API one of the most used API standards now the problem with API design is we have all these resources and we also have this common standard which is called a rest API or restful API standard and years of research and many many developers
particularly backend Engineers experience over the years and but still even now when someone who is learning backend or in the early stages of their journey into backend engineering they still get confused by certain questions questions like should the URI path segment be plural or singular or when updating a resource should you call patch or should you call put right
different different http methods and also if it's a non- crud operation meaning if it's not a fetch operation or create operation or an update operation or a delete operation it's it's a custom action something that you want the server to perform it's called an action call so which method should you use since it it sounds like update should you go with patch orput or since it's creating something should you post etc etc like questions like these and also
what uh HTTP status code to use for different different scenarios a lot of questions like this even now we still get confused about all these questions and the reason is when people were developing these standards uh these widespread HTTP API standards the state of the internet and the state of the web and the state of the clients and the state of the servers were very different from what we have today and and previously when these standards were
being developed we were heavily using MPS also known as uh multi-page applications and these days if you uh are aware of the front end side of the ecosystem then we heavily make use of single page applications know where in the first API call the browser makes a request and downloads all the JavaScript that is required required and it performs all the routing on the client side using the browser's path and URL
etc etc it's a completely client side a client heavy application now the purpose of this video uh is to standardize not to create new standards but as the standards already exist to extract certain rules and guidelines from this existing standards we aim to stick to these guidelines to make it as convenient as possible possible for everyone to follow A single standard and a consistent styling pattern when
designing apis know designing apis designing payloads and documentation etc etc everything surrounding API design this way we won't have to question these issues anymore these common issues that backend Engineers face in day-to-day lives we can simply move forward with our development now we already have this standard in place and by sticking to them we can focus on our business logic instead of worrying about whether our API is restful or not or whether we are
following the latest industry standards or not etc etc so in this video we will explore API design from end to end starting from how to design your resources how to design your routes how to return success responses how to return error responses which status code to use what kind of data to accept and much much more essentially everything related to API design so that we can concentrate on our business logic after this video we can move on from standards and we'll get into execution phase now
before we start about the technical stuff the actual API designing part let's talk a little bit about the history of where we are coming from and why we are talking about it so that we have a little more context so in 1990 Tim berners Le started a project called the worldwide web to share knowledge with the whole world that was the initial motivation for starting what we
call as Internet today and this project was built to facilitate the sharing of knowledge and information globally and with that goal team mesly within a year or so invented all these different concepts or Technologies first one URI what we call as uniform resource identifier second one HTTP the HTTP protocol that uh we use underneath to communicate between client
and servers we have already covered how HTTP works and etc etc in previous video so you can check that out third HTML HTML is basically the markup language which we use to construct web pages what you can call is the skeleton of a page fourth the first web server fifth the first web browser and sixth the first what you see is what you get editor an HTML editor which was built directly into the browser now he built all these
things which we still use today by the way and we use the advanced and the more developed version of all these Technologies we still use Uris we still use make use of HTTP protocols now uh it started with HTTP 1.1 then now we have HTTP 2.0 and 3.0 etc etc we still make use of HTML right we still use HTML we have a lot of different types of web servers these days we have a lot of different types of browsers these days etc etc and we also have the browsers uh in built
HTML editor right so he invented and he came up with all these new technologies and Concepts within an year or so but soon now the problem arises the problem was the project which was known as the worldwide web was headed towards breakdown because of the exponential growth of its user base within a short period of time a lot of users a lot of people started using this new technology
which is known as the worldwide web and the Creator uh Team Bal Le he had not accounted for all this uh scale all this number of users when he was building the project this was not accounted for so to scale the web to accommodate this large user base new techniques standards and components had to be introduced the previous one the all the mindsets and all the Technologies and all the
planning that went behind creating or coming up with all these Technologies was not enough to scale the web to account for the huge user base that it was acquiring every day it was scaling exponentially now at this point we have one other major contributor to the project web so around 1993 Roy Fielding the co-founder of the Apache HTTP server project became concerned about the web scalability problem that we just talked about the
web was not ready to accommodate this large user base the thousands and thousands of users and people that were using the worldwide web project every day to address this issue uh and make the worldwide web more scalable he proposed a couple of constraints that could help achieve the goal and these constraints are number one client server which we still follow by the way the client server model this constraint basically emphasizes the separation of con concerns between the
client and the server the client handles all the user interface the user experience while the server manages data storage and business logic which we also call as the front end and back end this separation allows each component to evolve independently and to improve scalability that's the first constraint the second constraint is uniform interface this constraint simplifies the
overall system architecture by establishing a standardized way a standardized way of components different different components that the web comprises of to communicate with each other it also includes uh four subc constraints which are called resource identification resource manipulation through representation self-descriptive messages and Hyper media as the engine of
application State we have also sub constraints under this one the uniform interface the philosophy of uniform interface the uniformity provides a consistent interface across all the services third one layered system now this says that the architecture composed of hierarchical layers and each layer can only see and interact with the immediate layer below it and this allows for better scalability security and the ability to add intermediate components like load balancers and prox servers Etc
which we use today to scale our web applications to cater to millions of users right and and this happens without affecting the system's core functionality now fourth cach cach uh responses from the server must be explicitly labeled as the cachable or non-cashable that's what this constraint says the server should label different different responses as whether it should be cached or not by the client and when the clients need they can cash the responses which helps reduce the server
load uh improve Network efficiency and enhance the user experience by providing faster response times now fifth one is stateless now stateless we have already covered in a much more depth in the previous video I think it was the HTTP video uh this basically means that each request from the client to the server must contain all the information necessary to understand the and process the request the server basically will not remember what your previous request was about with each request you have to include all the information necessary uh
so that the server can identify you and the server can take your data understand it and process it that's what stateless means and the server does not store any client context between requests and this in turn improves reliability scalability and visibility since any server can handle the request let's say you are scaling your web application and you have added two more servers and there is a load balancer in between which forwards your traffic depending on
different different algorithm like round robin etc etc and because of this stateless constraint all the servers can process request from the same client because of the statelessness nature of the web because all the requests consist all the information that the server needs to process the data and the sixth one which is code on demand this is an optional one uh which means that servers can temporarily extend client functionality by transferring executable code like JavaScript to the client and
this is only an optional constraint in rest architecture because it provides flexibility to add client side functionality when we need it uh while maintaining other constraints and etc etc this is not something you will see getting used heavily these six are basically all the constraints that Roy Fielding came up with to solve the problem of scalability in web and later on Fielding worked with Team Berner Le and both of them together worked to
increase the scalability of web and and to standardize their designs and together they wrote a specification for the new version of HTTP which we today know as HTTP 1.1 the first major version the first standard version of the HTTP protocol and then in the year 2000 after the scalability crisis of web was avered Fielding Roy Fielding named and described the web's architecture style
in his PhD dissertation and it was called as rest representational State transfer which was Roy fielding's PhD dissertation that was the name that Fielding gave to his description of the web architectural style and which today we know as rest apis and if you go and search Roy Fielding rest paper you can directly open this and and read the first document that was written about Rest apis by ra fielding and you can get
more insight more context and what uh LED them to come up with all these patterns come up with all these Concepts etc etc right it is a must read if you are a backend engineer reading this gives you a lot of context about where all these Technologies originated from all these Technologies patterns standards that we have today okay great now that brings us to why is it called a rest API what does it actually mean if
you read the paper that was uh written by Roy Fielding you'll definitely get the idea why was he calling it rest architecture or restful architecture or rest API but if you want to make it brief why the name rest why the name representational State transfer then we can up with some points number one is representational the first part of this name r which means representation this
basically means that resources on the internet resources on the web which means data or objects are represented in a specific format they have a specific representation depending on the specific servers and specific clients and these representations can be in various formats it can be in Json that is the most popular uh representation format that we have these days but we also have
XML and we also have HTML so different different representations depending on different different context for example a server to server communication will depend on the Json based representation while a server to client based communication depend on the HTML ml based communication right that's what representation means when we are talking about web's architecture the rest API architecture the same resource can have
different representation based on the client's needs so a user for example let's say we have a user resource which might have different different fields an ID field a name field a created at field etc etc so let's say we have a user resource a database resource let's assume so a user resource this can have different different representation depending on different different clients let's say this can be represented as a Json right for an API client let's say
another server is making a request to get this object or get this resource then this can have a Json based representation but if we want to send some uh UI data to the browser then we can represent this as an HTML document or as some kind of HTML representation right for the client which is a web browser so that's what we mean by representational in the restful architecture coming back to the second part state representational state transfer so what do we mean by state
here State basically refers to the current condition or attributes of a particular resource the current property of a resource the state of the resource and each resource let's say we had a user resource here so each resource has a state that can be transferred between client and server and the state is driven by the resource representation so taking an example let's say we have a uh
e-commerce site let's say we have Amazon we have Amazon and we have a shopping cart in the cart we have a couple of items so a shopping cart State includes all the items the quantities of the items and the total price so that we can call as a state of a particular resource of a particular module that we have in our web application that is transferred between a client and a server with each
API call and the last part which is transfer representational State transfer the third part talks about transfer what does transfer mean so transfer basically indicates the movement of resource the movement of resource representations between client and server so obviously since we have a client server model the primary intention of that is sending data between client and server and the client and server can exchange different representations of the same resource we have a client here and we have a server
here and the transfer of data happens uh through a common standard which is HTTP and we have uh different different methods associated with that which is get post uh put delete patch options head etc etc right we have all these different different uh methods which we use to send data between client and server for example when you get a web page when you uh send a get request to a
server for a web page you are transferring a repres presentation from server to client using an common HTTP method which is get so when we combine this when we combine all these three elements uh which is called representational State transfer or also known as rest or restful or rest API this describes an architectural style where one resources are representated in different formats we have different
different formats we have J on we have HTML we have XML etc etc first thing is resources have different different formats second the state of these resources can be transferred between server and client client and server first is the format of the resource the second is the state of the resource third clients and servers communicate between each other by sharing these representations of a resource okay the representations can be different but the
idea is client and server communicate with each other using these representations and third the system this whole system follows specific constraints specific constraints to make the whole workflow more scalable right which we have already discussed so that's what we mean by restful API or rest architecture that's the history behind uh where and when and how we came up with this whole architecture this whole model of representing resources
and transferring resources between client and servers and different different formats etc etc right this is all the theory that you need to understand on a very high level you don't need to remember any of it but this gives you a little bit of context of where and how we came up with all these things and where are we currently let's start with a URL and this is what a typical high level structure of a URL looks like know in any website that we visit this part what we call is the
scheme uh whether it can be HTTP or it can be https the secure version the encrypted version then we have the authority or the domain it can also have a subdomain but in this case we have the main domain which is sly. XYZ then we have the resource or the path so this part uh uh is called the resource that we are trying to access and this symbol the forward slash symbol represents a hierarchical relationship
between different resources and then we have the query parameters which we use in usually get apis to pass some kind of key value pairs to give more information to server about uh some kind of filters parameters etc etc then we have fragments uh this section usually uh navigates you to a particular section of a web page if this is present in the URL when you first time navigate to a web
page if you have a fragment then the browser Scrolls you to that part of the page okay so this is what a typical uh website URL looks like now we since we are talking about apis and best apis starting from this what would a an API URL or an API route will look like so we can start from this we will obviously have the scheme so let's imagine we have the encrypted version the secure version htps then we will have a subdomain so
I'm talking about the industri standard right this is not a rule uh this is more of a standard or best practices that most companies follow uh when they are implementing when they're creating their backends so usually it starts with a subdomain of the main with a subdomain of API so API dot let's say example example.com okay this is the subdomain part subdomain part then we have versioning most apis implement or follow some kind of versioning pattern and usually through routes so this will
follow something like V1 or V2 etc etc then we reach the path or the resource that we are trying to access so let's imagine it is a it is an API which is like good reads if you are aware of good read it's a platform where there are a lot of books there are a lot of authors and books are associated with authors you can provide your reviews feedbacks etc etc it's a whole community about readers and authors and books Etc if
this API is of good RS then an apaa which fetches all the list of books will have something of a structure like this so then we write the name of the resource so book now the first rule is in an API when you're designing a route when you're designing an API in the path segment whatever resource that you you are providing whatever resource your
client is trying to access or whatever resource the backend is serving that should always be in the plural form it is a standard that all the resources in your path segment of the URL should be of plural form so ideally it should be books okay then we have this API uh which has the subdomain api. example.com SL we have the versioning here and then we have books this is an API to list all the books to fetch the list of all books
similarly we can have another API so let's say we remove this this this let's say we have another AP which fetches a single book so up to this point we have bit constant right uh of course the we can have different different versions of the same API but for the sake of this example let's imagine up to this point we are in the version one only and this part is constant we will have the scheme https then we will have the subdomain
api. example.com then we'll have the version in which is the V1 but in the second API we want to fetch the information for a single book so what will the path look like now there is one mistake here which most people do is since we are fetching the information of single book uh people make this as a singular now right they make this slash book or then whatever the book ID etc etc you should not do that because um
even though you are fetching the information of a single book but the resource that it is concerned about this resource which is the book resource that is represented as a plural noun when we are dealing with path segments in the URL so even if this is about a single book we have to put we have to make it plural here so it will still be books then we have the ID now uh since we are talking about URLs one thing that you
have to uh keep in mind when you're are designing apis are the readability the representation of URLs in browsers or different different client environments couple of things that you have to remember is you should not put spaces or under scores etc etc these characters in a URL whether it can be a uh slug or whether it can be an ID know whatever part that you're dealing with for a route you should not put spaces or
underscores in a URL the thumb roll is if you have a phrase which has spaces and you want to put that into the URL let's say uh we have this API and we want to fetch the information of a single book and we want to fet the information using the slug of the book now slug is basically the name or some property of the book let's say the name of this book is Harry Potter the name of this book is Harry Potter now the slug
of this book will be a human readable representation of some property of that resource which is ideal to put inside a URL which means first thing that we do to convert this into a slug is we make all of this a small case even though we can put Capital case but because the URL will be traveling to different different environments it will travel to different server environments different client
environments different operating system we don't want to mess with the case mismatch etc etc right so first thing that we'll do is we make both of this as smaller is the first change is the part okay this is the first change second every time we have a space we will replace that with a hyphen now we have the final slug which is Harry Potter and now we can put this into a URL so/ book
SL Harry Potter one thing that I mentioned a while bag is I said whenever we use this character the forward SL character in a URL uh uh in an API route in a path segment this means there is a hierarchical relationship between these resources so for example this API this says that we have a resource a collection of resource which are called books in our server in our database or
wherever your storage is and that is the first level of hierarchy the second level of hierarchy is we want to access one particular resource from that collection of resource that resides in our database or some kind of storage so this is what I meant whenever we use the path segment you have to uh think of this as a hierarchical relationship between different resources okay so I think that's pretty much all the primer about URLs uh that we need to talk about
right now we'll of course explore more about how to design your routes in different different apis when we get to the demo part okay so moving on another important concept that we have when we are talking about restas is em potency this is a very important theoretical concept uh of course it has a practical implication but the concept of item potency basically means the property of certain operations in which
performing the same action multiple times has the same effect as performing it once which means an action which you have performed using an API call it does not matter how many times you perform that action the effect the side effect the change that happens in that environment Remains the Same it does not matter how many times you perform that action that's what we mean by em potency so in this context in the context uh where we
are talking about rest apis item potency basically means it does not matter how many times the client performs a particular request the outcome the result of that request in the server environment Remains the Same so even if I call an API once or I call the API thousand times the outcome of that the result of that should be the same if we call a particular API or a particular
action is item poent now as you already know when talking about different different actions that we can perform using API calls we come to the concept of HTTP methods and in the previous video of HTTP we have already discussed this in depth what are the different types of methods how they work what are the properties Etc ET so we have around five major kinds of methods that we use to handle different different data operations okay we have get we have post
we have put we have patch and we have delete okay these are the five major methods we have other methods also head and options etc etc which um head is used to patch the headers information and options is used to uh options is used in our course flow to find out whether the origin is allowed or not etc etc right but majorly these are the five kinds of methods that we use for data transfer between clients and servers now relating the concept of emut see two s
methods uh gives us a lot of insights into which method should we use in which context okay now the get call which we usually use to fetch some information from the server now this method is used to retrieve data from a server and it is em potent a get method or a get action on a server is considered as item poent because it does not matter how many
times you perform a get request you will get the same outcome right let's say we in the previous example we are fetching a list of books we fetching a list of books so it does not matter how many times you call this API you'll get a list of books and now you must be thinking what if uh while you're are making these API calls someone else creates another book and the result changes the response of the API changes in the subsequent calls of the G and and
that's true but that is not what we consider when we are talking about item poent item poent basically means from the client using an API call what side effect can you cause in the server and whether that side effect is different with each API call or that remains same during the first API call or the 1,000 API call okay now and because of that reason the get call is considered item poent it does not matter how many times you fetch some information you do not make any change with your API call in
the server environment okay it is just a fetch operation that's why the get is called an item Buton method similarly the patch method and the put method these two methods that we generally use to update some data in the server to update a particular resource or a part of a resource we use patch when we up we want to update a part of a resource let's say a single single field or two three fields of a resource in the server in that case we use patch we use put when we want to completely replace the
representation of resource in the server using the client payload so let's say we have a user object in the server it has ID it has name it has created at etc etc and for an update operation if we want to update the name of the user if you want to use the p method then we can just send the name field with the new value of the name and the server will handle it accordingly it will just update the name but using put method
what it does we have to send both the ID the name the created all the fields in that payload so that the server can take that payload and completely replace it with whatever instance of that user object the server has currently now it is true that um most of the time put and Patch is used interchangeably and that is fine that is fine to some extent uh as long as you using your API internally but let's imagine you are building some
kind of public API in that case you have to implement your API specs in a way that sticks to the standard as much as it can so that other people other Engineers who want to integrate your API do not get confused because they assume that you are following a standard but you are not so if you are using put when you should be using patch then that gives some kind of wrong assumption and it might be a confusing situation but
again it does not cause as much of a harm because obviously from the behavior of the a people can tell whether it is a patch operation happening or I put operation but yes uh you should always try to stick to the standard stick to the semantic standard that the rest a offers so if you want to update a particular resource partially then use patch if you want to completely replace the representation of a resource then use put okay now patch and put are also called as emed because let's say we are
updating the name of the user with a new value let's say the previous name of the user was a and we want to replace it with the new payload which is B okay so we make our first API call and we send this payload okay and the name of the user becomes from A to B that's the side effect that we caused using our API in the first API call what happens in the second API call the name of the user is already B but we make the same API call with the same payload now from B it
again changes to B okay now that continues it does not matter how many times you all that API it can be thousand it can be million but the result will be same after each operation the state of the user Remains the Same the name is still B you are not causing different side effects with each API call that's the reason patch andp put any kind of update operation with the same payload will obviously be item now we have ruled out get and patch and put
as uted methods next up is delete now what do you think delete is whether it is item button or not now imagine again we have this user object uh which has an ID name and created at field and we make a delete API call to the server and we deleted this user this user does not exist that is the result of the first API call what happens in the second API call you make the same request to delete
the API uh to delete the user which has the ID as one okay you made the same API call in the first payload with the user ID one and you are making the same API call again with the user ID on you want to delete this user in the second API call since this user is already deleted the server checks your payload it checks whether the user exists or not and it sends you an error that this user does not exist it sends you a 404 error since
you are trying to perform some action on an entity which does not exist that's the reason you are getting a 404 error but did you cause any side effect in the second AP go you did not because in the first API call you deleted the user in the second API call nothing really happened the server just checked whether the user exists or not and it send you an error but nothing really changed no state of the entity changed in the server it it had no side effects that's
the reason it does not matter how many times you call this delete API call you can call it a million times you'll get the same error million times that this user does not exist you only made the change in the first API call and that's the reason delete is also considered as an item poent method at last we reach post now this is the only method in the HTTP semantics which is considered as a nonm poent method
because when we use a post request usually the post request is used when we want to create a new resource or a new entity in the server so taking from our previous example which was a book API if you want to create a new book we want to add a new book to our inventory in that case we'll send the name of the book and some kind of description some kind of um weight Dimensions Etc different
different properties of the book and we will take this payload put it in the body and we send this to the server in a post call and the server receives it it takes the payload and it performs some kind of database operation and in it inserts that uh entity into the database it creates a new book now that's that's what happened in the first AP call in the second API call let's imagine you made the same payload with the same name
description ion bit Dimensions etc etc you just took the Cur of that request and you executed that Cur again you made the same API call again what happens now there is a chance that um in this API the name has to be unique if that is one condition that your server is following or your database is following then you might get an error which is the name cannot be duplicate ET
but for the sake of this example and it for the sake of real world scenario it is often the case that names can be duplicated right multiple books can have the same name right the that's that's the reason we differentiate between different books from their IDs not from the names so that's the reason uh when you make the same API call in the second time what happens the server takes your payload it performs the same operation and it inserts it into the database now you have the second book with the same
information right but with a different ID IDs are usually generated at the database level uh whether uu ID or some kind of Serial value 1 2 3 4 ET IDs are generated at the database level that's the reason you can have multiple books with the same kind of properties name description weight Dimensions etc etc but the IDS will be different that's the reason an error does not occur that's the second API call and this is the pattern with each API call you are creating a new book and when you if you call this API a thousand times you'll have a thousand new books now what we
discussed what is the property of what is the condition of idency the side effects that you cause in the server should not be different with each request right but it's the opposite happening for the Post calls right with each API call you are creating a new book the side effects are changing and that's the reason post request post methods are are called nonm poent Methods now one more thing about post is whenever we have a noncured operation an operation an action that does not fall
under any of the methods that is defined by HTTP spec right it is not a fetch operation it is not an update operation not a create operation not a delete operation it does not fall under any of the methods in that scenario because of the existence of scenarios like these the s spec the rest AP spec has made the post method as open-ended which means whenever you find yourself in a scenario where you cannot put some action
some uh action in any of the existing methods then you can put that under the post call in the post method so let's imagine we have an API which uh says we which is like send email okay we have this AP and when we call this we can send an email to a client so let's say the payload the body of this API call looks something like this target is some email address right and when we make
this API call the server takes it and extracts the payload the target email and sends the email that is basically the functionality of this API now the point that I'm trying to make here is what HTTP method that you would assign to this action or this API because it say send email but is this a fetch operation it's not right it is some kind of action we want to tell the server that do
perform this action whether it is a create operation it's not it's not an update or delete operation either that's the reason it is called a custom action in the HTTP or rest AP terminology so whenever we have scenarios like is whenever we have custom actions the operations or API calls which we cannot categorize under any of the Curr operations those are the situations that we can make use of the post method which is meant to be used for custom actions
as for the rest TP specification okay and that's pretty much all about HTTP methods uh when we are talking about rest apis now let's move on to some demo right how exactly do you start with your API design how do you actually design the interface for your API the interface that other clients whether it is server based clients or browser based clients any kind of clients can uh talk to can
interact the first thing if you are a backend engineer the first thing before you start coding before you write any of the business Logic the first thing you should do uh while creating an API is designing the interface for the API the interface should be intuitive it should be delightful to use and it should not be vague it should follow most of the standards of uh rest apis and the reason
for that is the reason for following standards the reason for following restful standards is to eliminate uh confus usion eliminate assumptions or any kind of human related errors in your whole workflow what that means is let's say you are designing your apis and you did not follow any of the standards and uh whenever you should have used put you used uh post and you
used delete operation to perform fetch operation ET ET you messed up the AP interface completely intentionally now as a result someone the consumer whoever that is any engineer who is integrating your API the only way the only way for them to find out all the behavior of your API starting from the successful Behavior and the error behavior and how the payloads are structured how the data
is structured and what uh method to call ET the complete API integration workflow for them to figure it out completely they have only two options they have to either read your code if it is open source or it is someone within your organization who has access to your code or they have to try out different methods and see as a result of the deoration if it is expected or not and you can see that that that's a lot of
room for error a lot of room for confusions and assumption etc etc now having a common standard and following a particular standard in your workflows especially when you're designing API interfaces gives you and all the consumers of your apis the advantage that they do not have to do any kind of guess work most of the behaviors are already defined in the standard so assuming that assuming the standards are
uh at least 80% followed in most cases the the effort and the time to integrate the API decreases a lot when you follow standards and uh there are less bugs there are less confusions and there are less synup calls with the uh whoever is integrating your apas Etc ET because all the uh you have been following all the standards the documentations are in place you have an interactive API uh playground etc etc now there is almost
no room for errors or confusions right that is the advantage of following standards following best practices so that the creator of the API and the consumer of the API already have some some kind of knowledge that this API will have these kinds of behaviors and there is no guess for involved there the first thing what is the first thing that you should do as a backend engineer when you are creating an API you should start with is from your UI design interface it
could be uh figma or any other kind of software that your designer or your product team uses to build wireframes or uh user stories etc etc now that's the place you should start with when you're designing an API because when you follow the wireframe you have an idea that how the end user not the frontend engineer the engineer F consumer API will interact with it you but you will have an idea that how the end user the users who are going to use your platform are
going to interact with data in general so uh usually this is how it works you have your users they interact with your platform the platform is built by your front end engineer and your front-end engineer consumes whatever API that you have built and you in turn interact with different different databases Etc as like you know the DB level so in a way when you look at the W frames the
designs of how the users are going to interact with your platform you have a very good understanding of how the user the first level of consumption are related to the last the low level of uh consumption which is the database right and forgetting about all this middlemen that comes into play whenever uh we have the whole SAS platform Etc once you have the clarity on how your
users are related to your data and that's an excellent point to start your actual API interface design because at this point you will find out what are the resources so since we are talking about restas the first important concept the first important entity uh that we should cover is resources now the resources are basically any any kind of nouns that you can identify from your wireframes or by
talking to your clients by understanding the requirements after you understood all the requirements whether by um from the whether from the wireframes or from talking to different people the product people or client people etc etc once you have the requirements from those requirements whatever noun you can find okay of of course this is an oversimplified uh definition of what are resource in a backend workflow but mostly this rule works this is a kind of
a thumb rule so whatever nouns you can find from there are your resources so imagine it is a uh project you are working on a project which is a project management SAS a project management platform okay uh something like uh jira or linear etc etc you working on a product which is similar to J linear which is a project management platform now after going through all the wireframes all the figma designs and
after talking to your clients your product people you can analyze your requirements and you can find out some of the nouns that come up in those requirements what could be some of the nouns the obvious ones are since this is a project management platform it will have projects right this is the first noun what is the second noun your users obviously it's a project management platform it will have users users are another noun then you can have organizations users can be part of different different organization so that is another uh resource that you can come
up with then each project will have tasks associated with it there is another noun then uh task can be um organized with different different tags so tags are another noun similarly as you can see the pattern once you have analyzed your figma designs you can easily come up with these resources and you can note it down and once you have all the resources noted down you have figured out uh what are the different different resources that your back end
that your platform will have okay the nouns the top level entities after this uh usually you jump into the database schema right since uh this video is only about the rest DPA side of it which usually comes after you have done with your DB schema designs the next video of course deals with uh all the DV schema designs and different different concepts of databases so we'll skip this part how you design your DV schema how you um interact with your databases all the
concepts surrounding Etc ET we'll leave this for the next video we'll focus only on the rest of part this is what the workflow looks like once you have identified all the resources from your fig designs you jump into your DB schema design and after you done with your DB schema design you get to your API interface design part since we are not talking about uh the DB schema design and all in this video we'll just do a very quick uh schema design so that we can continue to the rest API phase of
the API design workflow since we have skipped the database schema design part which we'll cover in the next video Let's imagine you are done with your databas schema design and you have these three tables okay uh since it's a project management platform you started with these three tables you have the organization table where you will keep track of all the organizations that exist in your platform then you have project uh what are all the projects that exist within an organization then
you have task uh inside task you will keep uh track of what are all the tasks that are created inside a project so for the sake of this demo and for the sake of this video uh we are building the API interface for a project management platform and we will get started with this schema design we have an organization table we have a project table have task table with this we will start our API design now the next thing to do we have already uh gone through
our figma designs and understood all the requirements we have come up with all the nouns all the resources that we have to create and using the resources we have created all the database schemas and now we have database tables now we have we already know the resources of our platform now we need to create apis for that the next thing to do since we already have this schema the next thing to do is finding out what are the actions that a client a typical client who will interact with your API needs to
perform on our server what are the actions and you can get started uh with some template actions using our crud API endpoints right uh a typical resource will have fetchall uh get a single resource update delete create etc etc right using that you will you will list out all the actions that you need to uh the users need to perform using your API which we usually call is CR operations
create read update and delete and after you know all the actions you'll jum jump into the API interface design part and for the API interface design part we'll use this Tool uh which is called insomnia uh it's an alternative to postman it is an alternative to postman but it has lesser features and it's a lighter in weight as compared to postman so we'll make use of this tool to uh design the interface of our API what
should the API of this platforms look like right remember we are designing the interface for this API which means that uh we are designing how clients who are going to consume our API who are going to integrate our API what the apis will look like how they will interact with etc etc right the interface point we are designing the interface Point not the execution point which includes writing whatever programming language that
you're writing your server in etc etc your actual business logic your database interactions Etc ET we are not going to cover that in this part we are only going to be concerned about the design of your API okay with that uh let's start so we have identified three uh major resources in our API which are uh organization project and task right so we have to design API surrounding these three resources starting with organization and we have also identified
what are the actions that clients need to perform with our a so according to those we have come up with five different kinds of actions for organization uh create organization get all organizations get a single organization and update organization delete organization etc etc right so let's start how the AP will look like I will create a new HTTP request so the first let's design the get all organizations AP so it is it will be a
get API because we are doing a fetch operation right now the next thing is we'll write the URL of our server now this is subject to change uh when you go to production uh the domain will change the scheme will change from HTTP to https and since I am running it in Local Host the scheme is HTTP and the domain is Local Host and my server is running on Port 3000 that's that and since it is just a demo we have not uh integrated versioning here but usually uh apis will
have some kind of versions here/ V1 then the actual path will come but here we are not doing versioning as of now so we are done with the URL part now comes the important part the actual route the actual path segment which is going to um identify what is that that we are trying to fetch from the server since it is an API so let's rename this to list organizations right list all organization so this is what it looks like right as I already said uh we
don't put Capital case in the path segment so we write organization and we have already mentioned that uh it should always be plural the resource part so it will be organizations this is what a typical list uh resource API looks like you have the domain you have the versioning if it exists and then uh the resource name in plural so this is ideally the list API and when we call this we are getting the empty response
okay the empty response so let's jump into the second API uh which is the create organization AP then we'll have a better idea about how the get one works right create organization and this will be a post operation because we are creating a resource in the server right it's a create operation that's why we are using the method post uh let's just copy this and paste this now here our URL looks pretty much the same for list organizations and for create
organization and the reason for that is the server differentiates between these two API calls using the HTTP method if it is a post method then this route goes towards the controller which handles creating an organization and if it is a get call with the same URL it goes to the controller which deals with listing all the organizations right so this is what a typical create operation for a particular resource looks like uh we have the as usual the servers address
and Slash the name of the resource in plural form okay now this is a post call so we have to attach the payload the data that the server needs to create an organization so if we look at the organization schema we have to exclude these three Fields these are database handled Fields right the ID the created it and updated it these are handled from the server side so we exclude these from
the payload now these three Fields the name the status and the description these three Fields can be passed from the client side using a pay Lo so let's pass these three name status and description name will provide as Arc one status since it's a Json payload we have to wrap all the fields in double codes so second is status status let's say is active and the last one is description is some some description right and these
are payload and when we run this we get this right we have have an ID which is created in the server s side and we have the created at which is also created in the server site and then we have the name status and description which we had passed in the payload that is provided here so this is the first thing that we should notice here in a typical post API call uh after calling the response is usually 2011 which we return when we
create a resource in the server if a new resource is created cre then we return the status code AS 2011 which means U created okay and then we return the newly created entity as it is in the success response that's why we have received the newly created organization here okay this is what the typical post interaction looks like now going back to our earlier list organization when we call this now now we are getting the entry the organization that we created
the organization that we created just now using the post call okay here the status code is 200 because 200 uh we return 200 status code when it is a successful response 2011 is when we create something but 20 is when it is just a success response we are sending some kind of data etc etc right this another thing to focus here is What's Happening Here uh we have a data field we have a total field we have a page field we have total Pages etc etc and this thing is called pagination the
terminology is pagination and why do we actually need pagination the need for pagination pagination is basically a technique uh which is used in server side when uh we are doing some kind of API call where a list of a particular resources returned in this case we are requesting a list of organizations whenever we have an API call like this which returns a list of some kind of resource and depending on the requirement we use this technique we implement this technique which is called
pagination what it does it does not return all the resources that exist in the database in the server side in that particular request right it returns a particular portion of the data in the response okay and since at this point we only have one organization so I cannot uh show you the difference but we'll create a couple of organization we'll see how the pagination works right so let's understand the theory first so this is the this is why we use pagination if we have a lot of data in the database and when the client makes
an API call so we only return a particular portion of that data in the response so that first thing Json serialization and deserialization as we have already covered in the previous uh some video that is a heavy operation right so if we let's say send a, organization in the response so serializing a th000 organizations into a payload which is transferable across uh internet is a resource heavy task right
it can introduce some kind of delay in our API it can have some kind of performance impact so that is one reason the second is if the server takes a little longer to send the response then the client uh the whatever the front end platform that is requesting that is using this API that will also have some kind of perceived delay and the user the end user who is using the platform they will notice the difference right they will notice there is some kind of 3
seconds and 4 seconds of delay that is happening because the client is fetching a thousand organizations in the list API call even though even though the on the first look on the first look when someone is using the platform they will only see let's say a 10 or 20 organization right if they want to see more organization they'll obviously have to scroll right now because of that kind of scenario people have come up with this technique called page nation in page Nation what happens in the initial call you return some portion of data
usually from the first and sorted by some parameter let's say the created parameter you return the latest 10 organization in the first API call right then when the user the end user clicks on page two or if it's an infinite scroll Scrolls down you make another API call and you say this part I already have give me the next portion this portion of the data right and then you take this and you show it to the user similarly when the user goes on page
three you ask for this portion and you s this data and this is how it works at at once you only fetch let's say 20 or 30 organizations and show it to the user so the user is also not overwhelmed network is not overwhelmed and the client in server perform better and that is the advantage of pation and this is often used whenever we are implementing some kind of list API so in this case we are listing organizations right that's why
we have implemented pagination here now the second thing to notice here is what are the fields that we are returning from in a pag response the first part is data whatever portion of the data we have to return that we return in the data field the second is total now this total field Returns the total count of all the organizations that is in the database and using this information the client can s some kind of metadata to
the user that um you have around 50 organization but at this page you are only viewing 10 right it can show some kind of UI like this 10 or 50 something something so for representation purpose for UI purpose we return a field which which uh shows the total count of all the resources that exist in our database which is independent of what portion of the data we are returning it is independent of the page response next is we return the Page Field uh which page
which portion of data that the server is is returning for this response this response which page it is associated with which portion it is right we have to assign some kind of number some kind of identifier the portion of the data that we are asking from the server that's the reason we call it a page and in this the server is saying this response is for page one you are doing page one then we return total Pages how
many pages in total there are and we can use this to show some kind of nice UI interactions or uh if it's an infinite scroll we can check for each time we are making the API call we can check whether uh the page and the total Pages if they are both same then we stop making the API call so because now that we know that uh we have reached the end of the pages right so this also provides some nice functionalities it helps the front
end make some decisions about whether to make the next API call or not etc etc this is what a typical paginated response looks like now let's go to the create a and create a few more organizations right let say organization 2 oration three organization 4 oration five okay we've created Five organizations and when we go to the list API and we call this we're getting all
five now that we have around five organizations how do we access let's see how the pageon actually works and how the client can ask for different different portions of the data using different different parameters since it is a get call the only way we can send data from client to server some kind of payload data is using query parameters now the server takes two kind of parameters for controlling how the pagination works the first one is limit
limit basically means what is the count of data that you want in each response since we have five entries five organizations what if we do limit is two each time we only want two organizations right the second parameter is page which portion of the data that you want by default if we don't send page and limit the server should and remember since we are in designing the interface try to
focus what are the points uh the server should Implement right if the client does not send anything in limited page the server should set some kind of default values for these so by default the server sets the value of page as one if the client does not send any kind of uh parameter in the page parameter same way the limit will be set to something like 10 or 20 if the client does not send it but here we are explicitly sending it so let's make this request
what happens when we do limit two and when we make this request the server returned us two organizations sorted by created at know the latest organizations that's why we are getting organization five and organization four because that's the order that we created we first created organization 4 then organization 5 that's why we are getting in this order okay second in total the server is returning how many entries are present in the database yes we have five organizations but we are returning two
okay because the client has passed the limit as two then which portion of the data that the server is returning which is which page the server is returning which is page one and how many pages are there in total there are three pages because if the limit is two and the total number of organizations are five then then to send all the data to clients the server has to make three pages in The First page there will be two entries in the second page there
will be two entries in the last page there will be one entry okay that's how pation works so when we do page as two and we keep the limit as two and then we make this request this is what we get we get organization 3 and organization two in the response basically we have this whole data portion where we have let's say uh organization 5 4 3 2 and one when we make page as one we get organization five and organization 4 basically this
portion when we make Pages two we get this portion right three and two and at the last when we'll make page three we should ideally get only the organization one because in the in the last page there is only one entry let's change this to page three and we got organization one and single response because we are asking give us the page three the last portion of the data so the total is five the current
page is three and the total pages is three okay these are basically the metadata about what is the current state of pation and this is how the client can and the client should interact with your apis right you should allow for a limit parameter and a page parameter so that the client can uh conditionally and programmatically access different different portions of the data so that's pretty much all about pagination how the server should Implement pagination okay a typical list API also has other parameters let's say let's get rid of
this okay let's get rid of these we don't want to uh look at page Nation anymore and when we send this we get all the five organization because by default the server sets the limit s 10 or some random value because even if the client does not send anything in the limit parameter the server should set some number as limit and page one as default parameters right now let's talk about sort in a typical list API we a server should also support sorting and this is
how it looks like we can pass one parameter for defining by which field we want to sort by okay it is typically written as sord by and here we can provide the name of the field that we want to sort by so here let's say we want to sort by name we are saying we want to sort by name okay and when we send this you're getting oration 5 4 3 2 1 okay no difference as of now now let's
add another parameter which is called sort order and here let's send ascending and when we do that here as you can see by default the server was returning all the organizations in the descending order so by now you should have realized this rule the rule that the server should ideally ideally take as many as it can s defaults and by S defaults I mean it should not depend on the client to send
obvious fields for example in a list API by default even if the client does not send anything we still got a response right we did not get any validation error that you are missing this parameter you're missing the page parameter um that made our whole experience way better because we did not have to pass obvious Fields obvious fields are such as page if the client does not pass the any explicit page the server should set the default pages one
similarly for limit if limit is not passed you should set a default limit either 10 or 20 something okay same way even if the client does not do any kind of manual or explicit sorting the server should do some kind of sorting by default so that the response of the data does not change between different different API calls if you don't sort by some parameter in the server before sending the response each time the
client makes an API call it will get the response in a random order because the database does not store and entries in any kind of sequence you have to explicitly do sorts that's the reason by default if you're creating an API especially a list API you should have some kind of default sort parameters so by default what uh we usually do we take the created at field take the created at field and we sort by this field and sort by what order we sort by descending
order now this is the natural state the default state of sort even if the client does not pass anything because it's a obvious response right we want to list all the entities all the resources in the descending order of their creation basically all the latest entries right that is a natural thing to assume from the server side that's the reason this is considered a s default when it comes to sorting scenarios in list apis but if the client does want to do some kind
kind of explicit setting the server should also support two parameters for sorts one is sort by by which field of the resource that you want to sort by it can be name it can be status it can be ID Etc it depends on your implementation but it should have some uh fields from the resource entry same way uh we should take another parameter which is called sort order what order the client wants the sort to happen in by default again
even if the client passes a sort by field you will still have to set the default that sort order if not passed you should set it as descending that is the reason when we did not pass any sort order we still got our data our response sorted by name in descending order because descending is the default state of sort order that the server sets even if the client does not send any sort orders but if the client sends ascending as sort order then the server takes that into account it takes the field it sorts
names in ascending order that's why we got organization 1 2 3 4 5 in the ascending order this is how sorting is implemented in a typical list API we have covered page naations we have covered sorting there is one last thing that is usually supported in a list API which is called filtering so let's remove this and and what filtering means is um even if it's a list API the client wants to filter that list by some parameters right so let's say let's go
and create an organization in the body we see organization as six and in the status instead of active we do archived and we create this and this is created and we got a 2011 response now we go to list and when we send this we are getting this or oration six the latest one right and the status is archived now what if the client has some kind of button some kind of switch using which the user can filter the list by saying I
only want all the organizations whose statuses are active or whose statuses are archived basically some kind of filter functionality and this is how we add support for filteration in a typical list API so so we take the name of the field uh so let's say the client wants to filter by status so we add a parameter which called status and inside this the client can pass what is the
status that it wants to filter by so if we pass archived and when we send this we only get the list of all the organizations whose status is archived same way if you pass active and when we send this we only got all the organizations which has the status as active and this is called filter okay and is just one field we can also filter by other fields so let's say uh we add
another parameter and the filter is name one the list of all the organizations whose name is let's say or and when we send this we are getting only one response because um in this scenario in this example we only have one organization which has the name r for and that's the reason the API is returning this okay so with that we have covered pagination filtering and sorting all the features that a typical list API should have okay now moving on let's
create an update API create a new request and it is a patch request right the thing is I have personally not used used a put implementation of an update APA as much because usually what we do we take some fields of a resource of an entity and we want to update those we never want to replace the whole entity with a payload that is passed from the client okay uh it it was usually a practice when we were building MPS or
multi-page applications but in the single page applications where the data is mostly Json heavy we usually pass partial fields of a resource and we only want to update those fields so mostly you will see patch getting used for update appear instead of put and that is usually best practice because um if it's partial Fields then patch conveys that semantic meaning in a better way as compared to put which is a little confusing uh but mostly developers use
put and Patch interchangeably so try to stick to the standards uh you patch whenever you are updating partial Fields oft a resource okay it's a patch request and we have to uh provide the servers URL so the servers URL is this one paste it here organizations now which organization that we want to update so this is where a dynamic parameter comes into play we have already explored what are Dynamic parameters etc etc and our routing video so for now we'll just go
ahead and use it so Dynamic parameter is usually uh some kind of string that we can arbitrarily pass so let's fetch the list and let's say we want to update this we want to update the status of organization 6 so let's copy the ID and we take the ID and let's rename this to date organization okay and as usual this is the server's address we have the path which is the plural form of the resource organizations and after this we write to
the slash we paste the idid of the organization and this is a valid route for a patch API con okay we want to update a single organization that's why we are passing the ID of the organization in the dynamic parameter now the pass request takes a body and we'll send a Json inside the Json want to update the status of the organization and the status is the existing status is archived we want to make get active Okay
and let's call this and we call this we are getting the organization six and the status is active we are successfully updated it the updated the value of the status field and when we go to the list API call and we call this we are getting the status is active for organization 6 now uh the typical response for an update or a patch API call the success response is uh the client sends the payload in the body and the server sends a 200 response since it did not create
any resource it is a successful API call that's why it is sending 200 the response the success response and in the response we are sending the updated data of the organization okay this is what the typical practice looks like for a patch IPI call now similarly what if we want to fetch the information of a single organization we want to patch the information so that's why it'll be a get call so let's first copy copy this and
create a new request let's rename this to get okay get AR and this is a get call and let's paste this one and getting the information of a single organization and updating the information of a single organization and deleting a single organizations mostly what you will see all these three apis the get update and delete for aing single organization the route will look similar we'll have the server address we'll have the path parameter with the plural form of the resource and with a
slash with a forward slash we'll have the ID in the dynamic parameters place okay this is what the route will look like and since it's a get call we uh don't pass any body or anything and we can just execute it and we got the information of the organization we have passed the ID of the organization 6 and we got the organization six with status code 200 because it is just a successful response we did not create anything we just fetched information okay at last we have a delete call we want to delete an
organization so let's uh create an HTTP request and rename this to Arc and the method is delete let's paste this as I said the get call update call and delete call of a single organization apis will look similar the route will look similar the only thing that will differentiate them is the method whether it is a get method whether it is a patch method or it is a delete method okay and we are not sending anybody we are just sending
the ID of the organization in the dynamic parameter and we execute this and when we execute this we do not get anything uh the response is empty but we got a different status code which is which is 204 which means no content the server is saying that whatever uh operation that you're trying to do it was successful that's why the status code starts with 200 series right 200 series all the codes in the 200 series are success responses whatever you're trying to do you trying to delete a resource that was
successful but there is no content I can send you because it is a delete operation and it is successful you successfully deleted the organization there is no information about the organization that I can send you that's what the server is saying that's why we did not get any response in the response of the delete API call and this is the usual practice whenever we have a delete API call uh we send an empty response with status code 204 and now when we go back and we get the list organization we
are getting the organization from organization 5 because we deleted the organization six and what happens uh when we come to the get call the get single organization API call and we run this we are getting organization not found as an error message and in the status code in the status code we are getting 404 so this is an ideal use case for status 404 which basically says that you are requesting a particular entity
you are requesting a particular entity a particular resource which has the ID this one and that resource does not exist in the server since we have already deleted this that does not exist in the server that's why we are wrting returning error code of 404 which means resource not pound okay but in the list API call we do not get any error even if there are no organizations in the list it is empty we still do not get an error because in list API call we are not
requesting for a particular resource we are requesting a list list of the resource right a list of organizations that is the reason we never send four or4 responses in list API calls a 404 response is usually sent when the client is sending a particular resource ID okay a particular resource a single resource or a bunch of resource in different different representations when the client request for a particular number of resources or a single resource that is the use case
when we should send a 404 but if it is a list API call and we don't have any data let's say the filter does not match any data let's say in the params we pass a filter so we pass status filter and here instead of active and archived we pass some uh random value some random value and when we execute this we are getting data as an empty array and total is zero page one total Pages zero this is the kind of response we get in a list API call this
response code is still 200 because it is a this is a list API call if you notice this we are not requesting a particular organization a particular resource that is the reason we should not throw 404 here even if we have no data for this filter we do not say resource not found we say the data is empty this is a thumb rule that you have to remember that if it's a list API call and there is no data you should return an empty array
with 200 response instead of returning 404 404 is only return When the client is requesting for a particular entity which does not exist in the server okay with that we have covered all the CED operations C basically means create read in the read we have get and list we have update and we have delete cow operations we have covered all the crow operations and this is how the typical crowd operations based API design interface will look like now what we have a custom
action by custom action I mean we want to perform some action on the server which does not fall under any of these categories it is not a create operation it is not a get operation or an update or a delete operation it is a particular action that we want to perform on a single organization entry let's say this is organization five and we want to Archive organization 5 okay now archiving an organization
you can on the first look you can imagine that if we update the status field of an organization to status archived then it is archived right so ideally it should fall under patch right but that is not the case you want to perform some action you want don't want to update an entity even though at the end of the day it is updating the entity uh you are updating organization five from status active to archived but at
the end of the day it is an custom action because let's say you want to Archive organization five right you want to make the status from active to archived now this is the action that you want to perform but you cannot simply just update the status field because when an organization is archived a lot of operations will have to be performed maybe all the projects that resides under that organization will also have to get get removed get deleted or some
kind of operation maybe the users that are involved in that organization have to be sent notifications or they have to be sent emails right and all the tasks that fall under all the projects that fall under all the organization they have to be deleted right lot of actions have to be performed from server side when a particular organization is archived that is the reason updating the status field of an organization from active to archived is not actually archiving an organization it at the end
of the day is an custom action you want to Archive an organization so now we have a use case where we want to perform some kind of custom action in this case the action is want to Archive a particular organization you want to perform this custom action on the server side for a particular organization right now as I have mentioned before whenever we have a use case which does not fall under any of the crud flows it is not a
create get delete or update method then we can use post with the custom action to construct an API call to execute that custom action in the server set so let's do that in the next API we'll create a new request and let's rename this to Archive archive organization right and here from the name also you can see that up until here we have crud endpoints we have delete get update create list right
from the names you can see that these are crud operations but at the end we have archive this is not a cud operation that's why we are classifying it as a custom action okay now how do you perform customer action we make it a post call we make it a post call then we take uh let's say uh let's execute this let's remove this and the ID of oranization 5 is this we take this ID let's paste this here and before that we need the servers address for that this
one is the address let's spacee this here and here we have the service address here there is the root path with the organizations then we have passed which organization like we want to Archive organization five that's why we are passing the ID of organization five then at last we want to write the action that we want to perform so in this case it is an archive operation this is an archive action we have written archive
now we have the route ready okay and if you notice here this completely follows a hierarchical relationship that we had uh mentioned earlier we have the service address so ignore this part from this path segment we can see that we have all organizations inside all organization we have a single particular organization and for that organization we want to perform some action so it is a clear hierarchical path that your API endpoint should ideally fall now when we execute
this we are getting a response and in the response we have the organization five and the status is archived we have made organization five from status active to status archived as a custom action with post end point right and even though we have used post here we still got the Response Code as 200 that's the reason you should not blindly assume that every post call will have
the Response Code of 2011 which is the creator Response Code because there could be also custom actions custom actions like these which will return 200 because they did not create any resource they will return 200 for custom API calls for custom action based API calls okay now with that we have covered all the API endpoints for the schema for the data model organizations okay now with
that we have covered all the API end points for organization this schema now let's move on to projects right we will do this one more time uh so that you can internalize all the patterns that we are using while while designing our endpoints all the patterns that we are using while designing the interface of our API okay okay so now let's continue designing all the apas for projects right projects endpoints so going back to
insomnia uh what I've done here I have created a folder called org and I've moved all the organization based endpoints inside the org folder so that it's easier to manage now that we'll be creating all the endpoints for projects this part is categorized as organization endpoints now we can minimize this create another folder and we'll name this as project and under this let's this let's create our first request which will be a post
request and this time we'll do this L still faster since I've already explained all the concepts behind it in the previous endpoint creation flows so this time we'll just uh Focus Fus on the patterns but we'll move faster so we have the servers address which is htdp Local Host and the port is 3,000 slash since we are designing now the endpoint for project that's why as our pattern says the plural form of the resource in small case which gives us
projects okay now this is for the post AP call okay now this route is ready now now what should go in the body since post request uh we are creating a new project what should go in the body a Json payload in the Json payload we can basically send name organization ID status description because the ID created at and updated at are server handle fields we do not uh accept that
from the client payload we are only accepting name organization ID status and description so name will be some project name then organization ID will be some organization ID that is already existing and the status will be let's say planned and the description will be some kind of description okay so let's come here and name is let's say project one then we have organization id id is some random ID for
now let's not worry about that then we have status let's say it is planned and in the end we have description the description we can pass some back okay now we have the payload ready now another thing to notice here is any kind of Json payloads whether it is a Json uh any kind of Json data whether it is a payload that we send from client to server or it is a response that we receive from server to client it should always follow the fields should always
follow camel case right that is a common standard when it comes to Json so that is something you have to keep in mind whether you are accepting payloads or you are giving responses from server side always try to stick to Json standards if you are using Json as your calization format uh that way uh clients do not have to do a lot of guess work because it is already established pattern that Json Fields always follow camel case okay now let's hit this and we got a status 2011 because a new
project is created and we got all the um fields that we have passed and the project entity that is created the typical create a using post let's go ahead and let's create another request and it will be a let's rename this to create project and we'll name this one to list project okay and this will be as usual a get call and we can copy the route of the post call because as I've
already mentioned the routes of create a resource and list resource will most of the time look similar and the routes of get a single resource update a single resource and delete a single resource will most of the time look similar because of the semantic meaning that comes with them right so we don't have to make any other changes here it is a list call and when we send this the server senses all the projects that is
inside the database okay so in the create one we can create a few more project two project 3 and in the list we can go ahead and we can do different different parameters can pass limit as one right if you pass limit is one we only get one response but when we add page with limit and the page is two here we are getting project three but when we are sending
limit one and page two we'll ideally get project two because it is the next portion of the data that we are fetching from the server similarly this will also have sorts this will also have filters that we have already discussed in the previous endpoint while we are uh dealing with list organizations endo right we have create projects and we have list projects now another thing I want to mention here is when you are designing apis uh for a particular platform right as long as you are inside a single project so all the apis inside
that project does not matter what the resources are here we have two resources we have organization and we have project but across different resources your query parameters and your Json payload should look similar and what I mean by that is let's say in the create organization if you see the body you can see the name uh the project has an organization has name and it has description and we are expecting those fields from the client now similarly in
the create project also we have name and we also have description that we are expecting from the client now the point I'm trying to make here is you should always try to be consistent when it comes to the Json payloads so so in the create organization API you made description the key of description like this so in the create project API also we have to uh you should keep the key similar you should not like go ahead and DSC right this also expresses that this field is associated with the description
field but since you already have an API where the Json payload contains a description field from that point on all all the apis that you design should follow a consistent pattern and if it's a description field then you should only uh then you should try to match that you should not try to rename Fields when the context is the same because because usually what happens when a front end engineer when some kind of client right
they integrate your API they consume one API they integrate one API and from that point on that frontend engineer that uh client they make a lot of assumptions of how your API functions they make assumptions that let's say this is a create organization API right from this point on when they want to integrate the project endpoints they will make a lot of assumptions that the since the project also has a name field since the project also has a description field
this is what the payload will look like for a project and it did look like that because that's the way you have designed it but imagine if you made the description field as DSC and the client the front end engineer without looking at the docs without looking at the specs of your API they executed the API right with the description field and they get a validation error now of course uh during development these kind of these kinds of things happen and that's totally fine but the point is you should not waste um
the people who are integrating your AP you should not waste their time and you should not waste their effort you should not make them do guess work right your API should always follow a consistent pattern whether it comes to routes or whether it comes to payloads whether it comes to responses always follow consistent pattern once you create an API stick to that standard whatever styling that you have followed stick to that not make arbitrary decisions across different different resources for
different different end points right always be consistent that's one of the most important characteristic of a good backend engineer the consistency of styling when it comes to API design similarly for list for create organization here we followed this pattern where uh the route is organizations the plural form of the resource now for the projects part let's say if we had did just project right now the person who is integrating your API judging and assuming from your create
organization API they'll they'll assume that the create project API must also follow the plural form right because that's what the organizations API followed so if you do not follow the same style if you do not be consistent then they'll also get an error at that then they have to figure out they have to read the specs they have to read the documentation etc etc right which is a lot of drag and that is the reason uh that is the importance of sticking sticking to a particular style sticking to a global standard now let's move on
let's create the rest of the apis we also have a get API let's create the rest of the apis we also have a get project API so what we can do copy this let paste this we have projects and up to this point we have to pass the project ID because it is a single project fetching API it is a get API which fetches a single projects that's why in the dynamic parameter you have to pass the ID of the project now let's execute this uh list projects and list
this parameters and execute this let's copy some ID and in this let's rename this one to project and let's paste this ID and when we execute this we got the response for a single project right ideally uh with the Response Code of 200 similarly let's go ahead and create the update API let's rename this project okay and here also we can let's copy the get project and here we can paste it as
I've already mentioned the routes of get single resource update single resource and delete single resource will always look similar because of the semantic meaning that they represent behind the scenes now this is an update API so will do patch because we are sending partial Fields right and this will re require some kind of body so this what should we update the description let's update the description we are say the description is the existing description is some
random value we'll change it so in the body we can send partial Fields so we just need to send the value of the new description field and here we can say that new description okay and when we send this we get a 20 when we send this we got a 200 response because it is a patch request and we got the updated entity and as you can see the description is new description yeah that's the typical behavior of patch
similarly let's implement the delete request this one inside project new request and let's rename let's rename this to delete project okay and we can just copy this because it is a single project API and we make this method as delete and there will be no body Etc right and I can send this and as usual since it is a delete method we got a 204 no content response and there is nothing
in the response because it is a delete request and at last we have a custom action so in case of project we have a requirement that the client the front end can clone a particular project and when they clone it what happens that project all the values of that project gets cloned and a new project with a different ID is created in the database with that other operations might also get executed in the server side which we don't know about that is the reason it is a custom action and it is not a
create action we could have also done that uh the client would also call the create project API and it could take all the values from the existing project it could pass uh all of them in the payload and create a new project with the all the same values it could simulate a cloning operation but but we don't know what clone means on the server side right if project clone can also mean that we have to take all the tasks that are inside that project and we have to also clone them right and maybe we have
to send an email to the owner of the project that your project have cloned ET right the server maybe has to perform a lot of other operations when a project is cloned that is the reason we cannot simulate cloning operation using just a create project API right we have to explicitly create an endo uh with a custom action for cloning okay so let's go ahead and do that let's create a new one let's rename this clone project and this will be post call as you already know all the custom actions which do not fall under any crud
operations are categorized under post because post is an open-ended method when it comes to rest APS specification so let's copy this one because the route will be similar we want to clone this particular project right let's paste this at the end we just write the name of the action this is how we designed a custom action based API we have the servers address we have the resource in the plural form we have the particular resource that we
want to perform the action on and at last the name of the action this is what the structure of the API looks like and it does not have any payload uh for this use case but maybe you can take payloads maybe you can take um some fields that the client wants to override for a clone operation okay now when we execute this we get a project not found and 404 response because we already deleted this project so let's go ahead and pick up a new project and replace this ID and then we execute this and we got it 20 one
response now as I said you cannot assume from the method that since this the post method it will be a 20 1 response or since it is a custom action it cannot return 2011 because depending on what happens on the server side the Response Code might change because during in cloning the server creates a new project that's why the server returned a response which says 2011 which means I created a new resource for you okay we got a 2011
response and the newly created resource and the name is Project to clone and all the fields that are similar to the project 2 entry that we had next this is the custom action based API for projects endpoint and with that all end points of project resource are completed hopefully by now you are able to establish all the patterns that goes behind designing all these apis and if you were to design all the apis for task so you would follow the same kind of pattern right you'll have a list API you'll have a get single
task API you'll have delete update and you'll have some kind of Uh custom action right the patterns are same does not matter how many resources do you have the patterns still remain the same with these patterns you can go out and design as many apis as you want right the basics are the same the foundation is still the same now with that out of the way there are a couple of things that you have to keep in mind while you are creating your apas to provide a good
experience to whoever is integrating your apas and whoever is maintaining your apas always try to provide an interactive documentation for your apas uh for for example start integrating Swagger tools like Swagger API which provide uh an interactive playground for trying out your apas right start planning that from your initial planning so that even so that you can use it to test your apas and whoever is integrating your apas they can use it as
a form of documentation and as a form of testing right that's the first thing this is very important and one of the most important things that sets part as a backend engineer how consistently and how frequently you uh create maintain and update your open API or Swagger documentation second thing is make your apis intuitive and consistent which I've already mentioned all your routes all the patterns when it comes to your
Dynamic parameters when you or custom actions or Json payloads all of them should follow a single pattern so if your following the global pattern the global standards of rest API then that's great right but even if you're not following that for some reason for some random reason that I cannot understand even if you cannot follow it but follow something right and stick to it do not change your styling do not change your
patterns of your API in different different end points across different different resources right that is a huge pain point for or whoever is trying to integrate your apis keep the behavior keep the data format keep the naming everything consistent and intuitive third provide CN defaults and by this I mean uh as we saw in the pag generation API right even if the client does not pass a default page the server sets the default page as one if the client does not pass a limit parameter the default
limit is 10 or 20 if the client does not part pass a sort field the default field is created at if the sort order is not passed the default sort order is descending similarly for post calls let's say there is a post operation in that case only require the amount of information that you absolutely need to create that entity otherwise provide some same defaults so even if it's a uh post call there are some fields for
example in our earlier create organization API there is a field for status if you see here the organization has a field for status which can have active or archived but judging from the business logic judging from common sense right you can assume that when an organization is created by default it should be in active state right so from the client if the client does not pass
the status field the server should by default set the status as active because it is a same default that part you can assume and it is a safe assumption so for feels like status you can take some status entry which makes most sense for your use case and provide that as a same default so that for creating an organization even if the client just passes name and a description and since
the description is optional here even if the client just passes a name this organization is is successfully created with status active because on the server side you have provided same defaults that's what we mean by same defaults both in get a calls in post a calls similarly always avoid abbreviations uh like DEC for description etc etc right because the amount of information you have while creating apis while creating the interface for your apas is not the same amount of information that the
people will have who are integrating your apis right so you cannot assume that if you provided some kind of abbreviation or some kind of short form of a field the people will be able to understand that and will be able to provide a appropriate entry for that field and that is the reason keep your peels whether it is payloads or whether it is query parameters keep them intuitive keep them readable and do not
use use abbreviations and stuff right now these are just a couple of things that you have to keep in mind while designing your API interfaces and that is pretty much all that I have about API designing uh hopefully it will help you uh make decisions make good decisions make decisions faster and stick to a particular standards so that it is easier for people who are maintaining your apis and it is easier for people who are integrating and consuming your apis in the future as a backend engineer
that's your responsibility to provide delightful to provide intuitive apis and always remember that an API a rest API at least is designed in the initial form it is not coded or it is not programmed right away at the first at the first phase of the API creation it is designed you have to make a lot of decisions to design your apis you cannot right away jump into programming that is the reason if you start uh with an open
API playground like Swagger or some kind of um API clients like insomnia or Postman to design the interface for your apis it will provide you more insights into how your clients or how the consumers of your apis are going to use it and that will make you think and that will make you make your apis in a much better way in a much more intuitive way and that is the reason before getting into
the coding part the programming of the API part regardless of the programming language that you're using whether it is go whether it is notes or any other language you should dedicate a separate session a separate session for just designing your interface the designing the interface for your apis without thinking about programming languages that's the reason in this video we did not uh talk about programming languages or language specific or framework specific implementation at all right we only focused on designing the interface
for our apis with this we'll end this video and ideally and hopefully you should be able to create delightful and intuitive apas from now on